package exec;

import java.util.Arrays;
import java.util.List;

/**
 * @Author wangj
 * @Date 2021/12/6 23:30
 */
public class LinkedOperation {

    private static ListNode head = new ListNode(-1);

    /**
     * 创建链表
     * @param value
     */
    static ListNode initLinked(int value){
        if(head == null){
            return null;
        }
        ListNode temp = head;
        while (temp.next != null){
            temp = temp.next;
        }
        temp.next = new ListNode(value);
        return head;
    }

    static ListNode initLinkedByList(List<Integer> list){
        ListNode temp = head;
        for(Integer i : list){
            ListNode listNode = new ListNode(i);
            assert temp != null;
            temp.next = listNode;
            temp = temp.next;
        }
        return head;
    }

    /**
     * 打印链表
     * @param head
     */
    static void printLinked(ListNode head){
        if(head == null){
            return;
        }
        if(head.next == null){
            System.out.println(head.val);
            return;
        }
        ListNode temp = head;
        while (temp != null){
            System.out.print(temp.val + "---->");
            temp = temp.next;
        }
    }

    /**
     * 指定位置插入数据
     * @param value 值
     * @param index index位置
     */
    static void insertListNode(int value, int index){
        if(index < 0){
            System.out.println("非法输入");
            return;
        }
        ListNode temp = head;
        if(temp == null){
            return;
        }
        if(temp.next == null){
            temp.next = new ListNode(value);
        }
        ListNode listNode = new ListNode(value);
        int i = 0;
        while(temp.next != null && i < index){
            i++;
            temp = temp.next;
        }
        listNode.next = temp.next;
        temp.next = listNode;
    }

    /**
     * 根据指定值删除ListNode
     * @param index 索引位置
     */
    private static void deleteListNode(int index){
        if(head == null){
            return;
        }
        if(index < 0){
            System.out.println("索引无效");
        }
        if(index == 1){
            head.next = head.next.next;
            return;
        }
        ListNode temp = head;
        int i = 0;
        while (temp != null && i < index - 1 && temp.next != null){
            i++;
            temp = temp.next;
        }
        temp.next = temp.next.next;
    }

    public static void main(String[] args) {
        List<Integer> integers = Arrays.asList(1, 2, 3, 5, 6);
        for (Integer i : integers){
            initLinked(i);
        }
        System.out.println("原始链表如下：");
        printLinked(head.next);
        System.out.println();

        insertListNode(4,3);
        System.out.println("插入4之后，链表如下：");
        printLinked(head.next);

        System.out.println();
        System.out.println("删除节点3之后，链表如下：");
        deleteListNode(1);
        printLinked(head.next);
    }
}

